/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.kai.wiki.util;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 *
 * @author Kenny Lin
 */
public class UploadUtil {

    public static Map upload(HttpServletRequest request, String destPath) throws UnsupportedEncodingException {
        request.setCharacterEncoding("utf-8");
        DiskFileItemFactory factory = new DiskFileItemFactory();
        String path = request.getRealPath(destPath);
        factory.setRepository(new File(path));
        //设置上传工厂的限制
        factory.setSizeThreshold(1024 * 1024);
        //设置一个上传的ServletFileUPload对象
        ServletFileUpload upload = new ServletFileUpload(factory);
        //设置一个保存非文件域的集合
        Map map = new HashMap();
        try {
            //处理HTTP请求，item是所有的表单项
            List<FileItem> list = upload.parseRequest(request);
            //遍历所有的表单项
            for (FileItem item : list) {
                //如果是非文件域就保存名称和值到map
                if (item.isFormField()) {
                    String name = item.getFieldName();
                    String value = item.getString("utf-8");
                    map.put(name, value);
                } else {
                    //取得文件域的表单域名
                    String name = item.getFieldName();
                    //取得文件名（各浏览器所取值不同，所以下面要进行相应的处理）
                    String value = item.getName();
                    int start = value.lastIndexOf("\\");

                    String filename = value.substring(start + 1);
                    map.put(name, destPath + filename);
                    item.write(new File(path, filename));
                }
            }
        } catch (Exception e) {
        }

        return map;
    }
}
